#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <pthread.h>
#include <unistd.h>
#include "Log.hpp"

#define PORT 8081
#define BACKLOG 5


class TcpServer
{

private:
    uint16_t port;
    int listen_sock;
    static TcpServer *svr;

private:
    TcpServer(uint16_t _port = PORT)
        : port(_port), listen_sock(-1)
    {
        //
    }

    TcpServer(const TcpServer&) = delete;

public:
    static TcpServer *GetInstance(uint16_t _port)
    {
        static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
        if (svr == nullptr) // 双判断避免后续锁竞争
        {
            pthread_mutex_lock(&lock);
            if (svr == nullptr)
            {
                svr = new TcpServer();
                svr->InitServer(_port);
            }
            pthread_mutex_unlock(&lock);
        }
        return svr;
    }

    int Sock()
    {
        return listen_sock;
    }

    void InitServer(uint16_t _port)
    {
        port = _port;
        Socket();
        Bind();
        Listen();
    }

    // 创建socket
    void Socket()
    {
        listen_sock = socket(AF_INET, SOCK_STREAM, 0);
        if (listen_sock < 0)
        {
            LOG(FATAL,"Create Socket Error!");
            exit(1);
        }
        // socket地址重用,当服务挂了可以立马重启
        int opt = 1;
        setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
        LOG(INFO,"Create Socket Success");
    }

    // 绑定
    void Bind()
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = INADDR_ANY; // 云服务器不能直接绑定公网IP，令随机绑定本机IP即可
        local.sin_port = htons(port);
        if (bind(listen_sock, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            LOG(FATAL,"Bind Error!");
            exit(2);
        }
    }

    // 监听
    void Listen()
    {
        if (listen(listen_sock, BACKLOG) < 0)
        {
            LOG(ERROR,"Listen ....Error!");
            exit(3);
        }
    }

    ~TcpServer()
    {
        if(listen_sock >= 0)
        {
            close(listen_sock);
            LOG(INFO,"Close Socket");
        }    
    }
};
// 静态变量在类外定义
TcpServer *TcpServer::svr = nullptr;